package com.lib.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;


import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;


import com.alibaba.android.arouter.launcher.ARouter;
import com.lib.app.ARouterPathUtils;
import com.lib.base.R;

import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.views.webview_x5.X5WebView;
import com.lib.ui.activity.kit.BaseActivity;
import com.lib.utls.picture_select.PhotoUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.ArrayList;

import androidx.annotation.Nullable;


public abstract class BaseWebActivity extends BaseActivity {

    private LinearLayout lin_web;
    private ProgressBar p_bar;
    private X5WebView webView;
    private FrameLayout.LayoutParams params;

    private View viewBg;

    private Handler handler = new Handler();

    @Override
    protected void onCreateView() {

        lin_web = findViewById(R.id.lin_web);
        p_bar = findViewById(R.id.p_bar);

        viewBg = findViewById(R.id.viewbg);

        webView = new X5WebView(this);
        params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        webView.setLayoutParams(params);
        lin_web.addView(webView);
        setWebView();
        onCreateView(webView);

    }


    protected abstract void onCreateView(WebView webView);

    protected abstract int getLayoutId();


    /**
     * 开始加载Url
     */

    public void setWebView() {


        try {

            webView.setWebChromeClient(new MyWebChromeClient() {

                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    super.onProgressChanged(view, newProgress);

                    if (newProgress >= 100) {

                        p_bar.setProgress(100);


                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                p_bar.setVisibility(View.GONE);
                                viewBg.setVisibility(View.GONE);

                            }
                        }, 250);//3秒后执行Runnable中的run方法
                    } else {
                        p_bar.setVisibility(View.VISIBLE);
                        p_bar.setProgress(newProgress);
                    }

                }

                @Override
                public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
                    return super.onJsAlert(webView, s, s1, jsResult);
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onBackPressed() {


        if (webView.canGoBack()) {
            webView.goBack();

        } else {
            finish();

        }
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {

            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = webView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webView);
            }

            webView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.clearView();
            webView.removeAllViews();
            webView.destroy();

        }
        super.onDestroy();
    }

    //---------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------文件选择
    //---------------------------------------------------------------------------------------------


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        LogUtil.e("===============requestCode的值为：" + requestCode + "===============resultCode的值为" + resultCode);
        if (0 == resultCode && 10103 == requestCode && data == null) {

            LogUtil.e("分享回调失败");
        } else {

            if (resultCode == RESULT_OK) {

                switch (requestCode) {

                    case PhotoUtil.WEBVIEW_IMGE:

                        // 图片、视频、音频选择结果回调


                        LocalMedia media = PictureSelector.obtainMultipleResult(data).get(0);
                        // 例如 LocalMedia 里面返回三种path
                        // 1.media.getPath(); 为原图path
                        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                        //linImage.removeAllViews();


                        if (media.isCompressed()) {
                            Uri result = Uri.parse(media.getCompressPath());
                            mUploadMessage.onReceiveValue(result);
                            mUploadMessage = null;


                        }


                        break;

                    case PhotoUtil.WEBVIEW_VIDEO:

                        // 图片、视频、音频选择结果回调


                        LocalMedia media2 = PictureSelector.obtainMultipleResult(data).get(0);
                        // 例如 LocalMedia 里面返回三种path
                        // 1.media.getPath(); 为原图path
                        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                        //linImage.removeAllViews();


                        Uri result = Uri.parse(media2.getPath());
                        mUploadMessage.onReceiveValue(result);
                        mUploadMessage = null;


                        break;

                    case PhotoUtil.WEBVIEW_Url:

                        Uri url = Uri.parse(webView.getUrl());

                        mUploadMessage.onReceiveValue(url);
                        mUploadMessage = null;

                        break;
                }
            }
        }

    }


    private ValueCallback<Uri> mUploadMessage;

    public class MyWebChromeClient extends WebChromeClient {


        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
            return super.onShowFileChooser(webView, valueCallback, fileChooserParams);


        }

        // Android > 4.1.1 调用这个方法
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            LogUtil.e("WebView文件选择" + acceptType);
            mUploadMessage = uploadMsg;

            if (acceptType.equals("image/*")) {
                addImage();
            }

            if (acceptType.equals("video/*")) {
                addVideo();
            }


        }

        // 3.0 + 调用这个方法
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType) {

            LogUtil.e("WebView文件选择" + acceptType);
            mUploadMessage = uploadMsg;
            if (acceptType.equals("image/*")) {
                addImage();
            }

            if (acceptType.equals("video/*")) {
                addVideo();
            }

        }


    }

    private void addImage() {
        PhotoUtil.normalSelectPictureByCode(this, new ArrayList<LocalMedia>(), 1, PhotoUtil.WEBVIEW_IMGE);
    }

    private void addVideo() {
        PhotoUtil.recordVideoByCode(this, new ArrayList<LocalMedia>(), 1, PhotoUtil.WEBVIEW_VIDEO);
    }
}
